# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from utils.views import AuthenticationExceptView, WdAPIView, WdListAPIView
from django.http.response import JsonResponse
import string
from models import User, ElevatorONLIne, ElevatorCollector, ElevatorCollectorOnlineRate, ElevatorStatus, ElevatorFault,\
    ElevatorEvent, ElevatorStatistics, ElevatorWarning, ElevatorFaultDeal
import time
from ElevatorAdmin.settings import MANUFACTURER_DICT, MANUFACTURER_COOKIE_LIVE, MANUFACTURER_VER, LC, CITY_CENTER_WB, RL, RLHOST
import random
from manufacturer.models import AuthorityCode, StatusMsg, AlarmMsg, ElevatorRegister
from serializer import AuthorityCodeSerializer, StatusMsgSerializer, ElevatorFaultSerializer
from basic.models import ElevatorInfo, ElevatorPersonInfo
from users.models import CompanyInfo, Person, AuthUser
import json
import datetime
from maintenance.models import Task
from ElevatorAdmin.settings import HOST
from models import PlatformSession
import requests
from utils.logger import get_logger
from ElevatorAdmin.settings import TO_GOV
from manufacturer.call_interface import device_status
from utils.request_rl import handler_lc_request_for_status


logger = get_logger(__name__)


def get_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    ip = x_forwarded_for.split(',')[-1].strip()
    # ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
    return ip


def get_now():
    return datetime.datetime.now().strftime("%Y%m%d%H%M%S")


def is_lc(lc_id, lc_ac):
    return lc_id == LC.get("id") and lc_ac == LC.get("ac")


def get_time(s=None):
    if s:
        try:
            t = datetime.datetime.strptime(s, "%Y%m%d%H%M%S")
        except:
            return ""
        else:
            return t.strftime("%Y-%m-%d %H:%M:%S")
    return ""


def get_alarm(a=None):
    alarms = {"0": u"无故障", "1": u"轿厢报警按钮", "2": u"电梯困人", "3": u"非平层停梯", "4": u"安全回路断路", "5": u"轿厢冲顶",
              "6": u"轿厢蹲底", "7": u"开门走梯", "8": u"电梯速度异常", "9": u"电梯运行时安全回路断路", "10": u"关门故障",
              "11": u"开门故障", "12": u"轿厢在开锁区域外停止", "13": u"轿厢意外移动", "14": u"电动机运转时间限制器动作",
              "15": u"楼层位置丢失", "16": u"其他阻止电梯再启动的故障"
              }
    if a:
        l = a.split(",")
        ret = []
        for i in l:
            alarm = alarms.get(i, "")
            if alarm:
                ret.append(alarm)
        return ",".join(ret)
    return ""


def get_maintain_type(t):
    if t % 40 == 10:
        return u"年保"
    elif t % 40 == 20:
        return u"季保"
    elif t % 40 == 30:
        return u"半月保"
    elif t % 40 == 0:
        return u"半年报"
    return ""


def check_session(session):
    b = User.objects.filter_active(session=session, expire_time__gt=int(time.time())).exists()
    return b


class FaultQueryListView(WdListAPIView):
    """电梯故障查询接口"""
    model = AlarmMsg
    serializer_class = ElevatorFaultSerializer
    # TODO 查询条件未知，后续完善


class StatusMsgQueryListView(WdListAPIView):
    """电梯运行状态查询接口"""
    model = StatusMsg
    serializer_class = StatusMsgSerializer
    # TODO 查询条件未知，后续完善


class LoginView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        data = self.request.data.get('login', None)
        if not data:
            return JsonResponse({"ret": {
                "login": [{
                    "c": "7",
                    "d": "parameter missing",
                    "ver": MANUFACTURER_VER,
                    "ses": ""}]
            }})
        manufacturer_id = data.get('id', None)
        authority_code = data.get('ac', None)
        ver = data.get('ver', None)
        timestamps = data.get('t', None)
        if not manufacturer_id or not authority_code or not ver or not timestamps:
            return JsonResponse({"ret": {
                "login": [{
                    "c": "7",
                    "d": "parameter missing",
                    "ver": MANUFACTURER_VER,
                    "ses": ""}]
            }})
        if TO_GOV:
            b = manufacturer_id == MANUFACTURER_DICT['id'] and authority_code == MANUFACTURER_DICT['ac']
        else:
            b = manufacturer_id == RL['id'] and authority_code == RL['ac']
        if b:
            session = "".join(random.sample(string.uppercase + string.hexdigits, 32))
            expire_time = int(time.time()) + MANUFACTURER_COOKIE_LIVE
            users = User.objects.filter_active(manufacturer_id=MANUFACTURER_DICT['id'])
            if users:
                users.update(is_active=False)
            User.objects.create(**{"session": session, "expire_time": expire_time,
                                   "authority_code": MANUFACTURER_DICT['ac'],
                                   "manufacturer_id": MANUFACTURER_DICT['id']
                                   })
            #
            #
            # # ip = get_ip(request)
            # users = User.objects.filter_active(manufacturer_id=manufacturer_id, authority_code=authority_code,
            #                                    expire_time__gt=int(time.time()))
            # if users:
            #     return JsonResponse({"ret": {
            #         "login": [{
            #             "c": "7",
            #             "d": u"还ip登陆前请退出之前所有登陆",
            #             "ver": MANUFACTURER_VER,
            #             "ses": ""}]
            #     }})
            # User.objects.create(manufacturer_id=manufacturer_id, authority_code=authority_code, session=session,
            #                     expire_time=expire_time)
            return JsonResponse({
                "ret": {
                    "login": [{
                        "c": "0",
                        "d": "success",
                        "ver": MANUFACTURER_VER,
                        "ses": session}]
                         }
                                 })
        else:
            return JsonResponse({"ret": {
                "login": [{
                    "c": "7",
                    "d": u"鉴权失败，请重新输入",
                    "ver": MANUFACTURER_VER,
                    "ses": ""}]
            }})


class LogoutView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        ses = self.request.data.get('ses', None)
        logout = self.request.data.get('logout', None)
        t = self.request.data.get('t', None)
        if not ses or not logout or not t:
            return JsonResponse({"ret": {
                "logout": [{
                    "c": "11",
                    "d": "parameter missing",
                    "ver": MANUFACTURER_VER,
                    "ses": ses}]
                }
                })
        if logout != "1":
            return JsonResponse({"ret": {
                "logout": [{
                    "c": "11",
                    "d": "the value of 'logout' was wrong ",
                    "ver": MANUFACTURER_VER,
                    "ses": ses}]
            }
            })
        now = int(time.time())
        # ip = get_ip(request)
        # user1 = User.objects.filter_active(session=ses, ip=ip).first()
        user = User.objects.filter_active(session=ses, expire_time__gt=now)
        if not user:
            return JsonResponse({"ret": {
                "logout": [{
                    "c": "11",
                    "d": "session not exist",
                    "ver": MANUFACTURER_VER,
                    "ses": ses}]
            }
            })
        user.update(expire_time=now)
        return JsonResponse({"ret": {
            "logout": [{
                "c": "0",
                "d": "success",
                "ver": MANUFACTURER_VER,
                "ses": ses}]
        }
        })


class BeatView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        ses = self.request.data.get('ses', None)
        t = self.request.data.get('t', None)
        if not ses or not t:
            return JsonResponse({"ret": {
                "hbeat": [{
                    "c": "11",
                    "d": "parameter missing",
                    "ver": MANUFACTURER_VER,
                    "ses": ses}]
                    }
                    })

        now = int(time.time())
        # ip = get_ip(request)
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "hbeat": [{
                    "c": "11",
                    "d": "session not exist",
                    "ver": MANUFACTURER_VER,
                    "ses": ses}]
            }
            })
        user.expire_time = now + MANUFACTURER_COOKIE_LIVE
        user.save()
        return JsonResponse({"ret": {
            "hbeat": [{
                "c": "0",
                "d": "success",
                "ver": MANUFACTURER_VER,
                "ses": ses}]
        }
        })


class ElevatorRegistryView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        # 写入数据库
        from users.models import SystemLog, LogRefresh
        er = self.request.data.get('er', None)
        ses = self.request.data.get('ses', None)
        lr = LogRefresh.objects.filter_active(service_id=0).first()
        ip = get_ip(request)
        if not ses or not er:
            logger.info("ses or er missed")
            return JsonResponse({"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                })
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            logger.info("ses not exist")
            return JsonResponse({"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses},
                ]
            }
            })
        # l = []
        data = {"ret": {"er": []}}
        for item in er:
            f = item.get('f', None)
            mn = item.get('mn', None)
            o = item.get('o', None)
            e = item.get('e', None)
            t = item.get('t', None)
            s = item.get('s', None)
            tm = item.get('tm', None)
            try:
                ElevatorRegister.objects.create(**{"f": f, "mn": mn, "o": o, "t": t, "s": s, "tm": tm, "e": e})
                data["ret"]["er"].append({"o": "1130", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})

                if lr and lr.refresh:
                    j = json.dumps(item)
                    text = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " 收到(" + ip.encode(
                        "utf8") + ") 注册信息" + j + "。"
                    SystemLog.objects.create(create_by=u"第三方平台", log=text, log_type=2)
            except Exception as e:
                logger.info(e)
        if not TO_GOV:
            return JsonResponse(data)
            # 转入市局
        url = HOST + 'api/platform/odev/eleregister.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['er']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorONLIneView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        ses = self.request.data.get("ses")
        eo = self.request.data.get("eo")
        if not ses or not eo:
            return JsonResponse({"ret": {
                "eo": [
                    {"f": "", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}
                ]}
            })
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "eo": [
                    {"f": "", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}
                ]}
            })
        # res = []
        data = {"ret": {"eo": []}}
        for dic in eo:
            f = dic.get('f', '')
            tn = dic.get('tn', '0')
            on = dic.get('on', '0')
            t = dic.get('t', '0')
            try:
                ElevatorONLIne.objects.update_or_create(defaults={"on": on, "tn": tn, "t": t}, f=f)
                data["ret"]["eo"].append({"f": f, "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
            except:
                pass
        if not TO_GOV:
            return JsonResponse(data)
            # res.append({"f": f, "c": "0", "d": "success", "ver": MANUFACTURER_VER, "ses": ses})
        # return JsonResponse({"ret": {
        #     "eo": res
        #     }
        # })
        url = HOST + 'api/platform/odev/eleregister.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['eo']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorCollectorView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        ses = self.request.data.get('ses', None)
        oo = self.request.data.get('oo', None)
        if not ses or not oo:
            return JsonResponse({"ret": {
                "oo": [
                    {"o": "", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}
                    ]}
                    })
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "oo": [
                    {"o": "", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}
                ]}
            })
        data = {"ret": {"oo": []}}
        for dic in oo:
            f = dic.get('f', u'')
            e = dic.get('e', u'')
            o = dic.get('o', u'')
            t = dic.get('t', u'')
            s = dic.get('s', 2)
            if int(s) == 0:
                s = False
            elif int(s) == 1:
                s = True
            t1 = dic.get('t1', u'')
            t2 = dic.get('t2', u'')
            try:
                ElevatorCollector.objects.update_or_create(defaults={'e': e, 't': t, 's': s, 't1': t1, 't2': t2, 'f': f}, o=o)
                data['ret']['oo'].append({"o": "1110", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
                if o:
                    ac = AuthorityCode.objects.filter_active(device_code_elevator=o).first()
                    if ac:
                        st = ac.is_online
                        ac.is_online = s
                        ac.save()
                        logger.info("is_online status has been update , the o is : %s, the s is : %s" % (o, s))
                        if st != s:
                            device_status.delay(ac.code, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
            except:
                pass
        if not TO_GOV:
            return JsonResponse(data)
        # return JsonResponse({"ret": {
        #     "oo": [
        #         {"o": "1110", "c": "0", "d": "success", "ver": MANUFACTURER_VER, "ses": ses}
        #     ]}
        # })
        url = HOST + 'api/platform/odev/odo.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['oo']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorCollectorOnlineRateView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        ses = self.request.data.get('ses', None)
        dr = self.request.data.get('dr', None)
        if not ses or not dr:
            return JsonResponse({"ret": {
                "dr": [
                    {"f": "", "t": "", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses},
                        ]}
            })

        now = int(time.time())
        ip = get_ip(request)
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "dr": [
                    {"f": "", "t": "", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses},
                ]}
            })
        l = []
        for dic in dr:
            f = dic.get('f', u'')
            t = dic.get('t', u'')
            r = dic.get('r', u'')
            tm = dic.get('tm', u'')
            ElevatorCollectorOnlineRate.objects.update_or_create(defaults={'t': t, 'r': r, 'tm': tm}, f=f)
            l.append({'f': f, 'c': '0', 'd': 'success', 'ver': MANUFACTURER_VER, 'ses': ses})
        return JsonResponse({"ret": {
            "dr": l}
        })


class ElevatorStatusView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        from users.models import SystemLog, LogRefresh
        lr = LogRefresh.objects.filter_active(service_id=0).first()
        ip = get_ip(request)

        ses = self.request.data.get('ses', None)
        es = self.request.data.get('es', None)
        # now = datetime.datetime.now()
        # today = datetime.datetime(year=now.year, month=now.month, day=now.day)
        if not ses or not es:
            return JsonResponse({"ret": {
                "es": [
                    {"o": "1110", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}]
                    }
                })
        now = int(time.time())
        # ip = get_ip(request)
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "es": [
                    {"o": "1110", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })
        data = {"ret": {"es": []}}
        for dic in es:

            if lr and lr.refresh:
                j = json.dumps(dic)
                text = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " 收到(" + ip.encode(
                    "utf8") + ") 运行信息数据" + j + "。"
                SystemLog.objects.create(create_by=u"第三方平台", log=text, log_type=2)

            f = dic.get('f', None)
            e = dic.get('e', None)
            o = dic.get('o', None)
            # u上行信号 只有0 1选择，如果不传就会报错
            u = dic.get('u', None)
            d = dic.get('d', None)
            lm = dic.get('lm', None)
            rs = dic.get('rs', None)
            od = dic.get('od', None)
            om = dic.get('om', None)
            sd = dic.get('sd', None)
            sm = dic.get('sm', None)
            ob = dic.get('ob', None)
            dz = dic.get('dz', None)
            ol = dic.get('ol', None)
            fl = dic.get('fl', None)
            ps = dic.get('ps', None)
            cp = dic.get('cp', None)
            t = dic.get('t', None)
            try:
                # es = ElevatorStatus.objects.filter_active(o=o, create_time__gte=today).first()
                # if not es:
                #     es = ElevatorStatus()
                # es.u = u
                # es.d = d
                # es.lm = lm
                # es.rs = rs
                # es.od = od
                # es.f = f
                # es.om = om
                # es.sd = sd
                # es.sm = sm
                # es.ob = ob
                # es.dz = dz
                # es.ol = ol
                # es.fl = fl
                # es.ps = ps
                # es.cp = cp
                # es.o = o
                # es.t = t
                # es.save()
                ElevatorStatus.objects.update_or_create(o=o, defaults={'u': u, 'd': d, 'lm': lm, 'rs': rs, 'od': od, 'f': f,
                                                                       'om': om, 'sd': sd, 'sm': sm, 'ob': ob, 'dz': dz,
                                                                       'ol': ol, 'fl': fl, 'ps': ps, 'cp': cp, 't': t})
                data['ret']['es'].append({"o": "1110", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
                if lr and lr.refresh:
                    j = json.dumps({'u': u, 'd': d, 'lm': lm, 'rs': rs, 'od': od, 'f': f, 'o': o,
                                    'om': om, 'sd': sd, 'sm': sm, 'ob': ob, 'dz': dz,
                                    'ol': ol, 'fl': fl, 'ps': ps, 'cp': cp, 't': t})
                    text = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + \
                        "  运行状态数据入库manufacturer_elevatorstatus表"+ j
                    SystemLog.objects.create(create_by=u"第三方平台", log=text, log_type=2)
            except Exception, e:
                logger.info(e)
        # try:
        #     j = json.dumps(es)
        #     logger.info(u"这是接收到肖老师或者日立的数据")
        #     logger.info(j)
        # except:
        #     pass

        if not TO_GOV:
            return JsonResponse(data)
        # return JsonResponse({"ret": {
        #     "es": [
        #         {"o": "1110", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses}]
        # }
        # })
        url = HOST + 'api/platform/odev/es.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data, timeout=5)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['es']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorFaultView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        ses = self.request.data.get('ses', None)
        ef = self.request.data.get('ef', None)
        if not ses or not ef:
            return JsonResponse({"ret": {
                "ef": [
                    {"o": "1121", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}]
                }
            })
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "es": [
                    {"o": "1121", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })
        data = {"ret": {"ef": []}}
        for dic in ef:
            f = dic.get('f', None)
            e = dic.get('e', None)
            o = dic.get('o', None)
            s = dic.get('s', None)
            a = dic.get('a', None)
            er = dic.get('er', None)
            t = dic.get('t', None)
            sn = ef.t + str(datetime.datetime.now()).split(".")[1]
            try:
                ElevatorFault.objects.create(f=f, e=e, o=o, s=s, a=a, er=er, t=t, sn=sn)
                data["ret"]["ef"].append({"o": "1120", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
            except:
                pass
        if not TO_GOV:
            return JsonResponse(data)
        # return JsonResponse({"ret": {
        #     "ef": [
        #         {"o": "1120", "c": "0", "d": "success", "ver": MANUFACTURER_VER, "ses": ses}]
        # }
        # })

        url = HOST + 'api/platform/odev/ef.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['ef']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorFaultDealView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        ses = self.request.data.get('ses', None)
        ef = self.request.data.get('ef', None)
        if not ses or not ef:
            return JsonResponse({"ret": {
                "ef": [
                    {"c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })
        if not check_session(ses):
            return JsonResponse({"ret": {
                "ef": [
                    {"c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })

        bulk_list = list()

        for dic in ef:
            e = dic.get("e", None)
            a = dic.get("a", None)
            er = dic.get("er", None)
            fid = dic.get("id", None)
            sp = dic.get("sp", None)
            st = dic.get("st", None)
            rp = dic.get("rp", None)
            t = dic.get("t", None)
            obj = ElevatorFaultDeal(e=e, a=a, er=er, fid=fid, sp=sp, st=st, rp=rp, t=t)
            bulk_list.append(obj)
        if ef:
            ElevatorFaultDeal.objects.bulk_create(bulk_list)
        return JsonResponse({"ret": {
                        "ef": [
                            {"c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses}]
                    }
                    })


class ElevatorEventView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        ses = self.request.data.get('ses', None)
        ee = self.request.data.get('ee', None)
        if not ses or not ee:
            return JsonResponse({"ret": {
                "ee": [
                    {"o": "1120", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}]
                }
                })
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "es": [
                    {"o": "1120", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })
        data = {"ret": {"ee": []}}
        for dic in ee:
            f = dic.get('f', u'')
            e = dic.get('e', u'')
            o = dic.get('o', u'')
            am = dic.get('am', u'')
            p = dic.get('p', u'')
            ss = dic.get('ss', u'')
            om = dic.get('om', u'')
            rm = dic.get('rm', u'')
            fm = dic.get('fm', u'')
            epm = dic.get('epm', u'')
            em = dic.get('em', u'')
            oc = dic.get('oc', u'')
            t = dic.get('t', u'')
            try:
                ElevatorEvent.objects.create(f=f, e=e, o=o, am=am, p=p, ss=ss, om=om, rm=rm, fm=fm, epm=epm, em=em, oc=oc, t=t)
                data["ret"]["ee"].append({"o": "1120", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
            except:
                pass
        if not TO_GOV:
            return JsonResponse(data)
        # return JsonResponse({"ret": {
        #         "ee": [
        #             {"o": "1120", "c": "0", "d": "success", "ver": MANUFACTURER_VER, "ses": ses}]
        #         }
        #         })

        url = HOST + 'api/platform/odev/ee.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)

        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['ee']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class ElevatorStatisticsView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):

        ses = self.request.data.get('ses', None)
        est = self.request.data.get('est', None)
        if not ses or not est:
            return JsonResponse({"ret": {
                "est": [
                    {"o": "1120", "c": "12", "d": "parameter missing", "ver": MANUFACTURER_VER, "ses": ses}]
                    }
                })
        # l = []
        now = int(time.time())
        user = User.objects.filter_active(session=ses, expire_time__gt=now).first()
        if not user:
            return JsonResponse({"ret": {
                "es": [
                    {"o": "1120", "c": "12", "d": "session not exist", "ver": MANUFACTURER_VER, "ses": ses}]
            }
            })
        data = {"ret": {"est": []}}
        for dic in est:
            f = dic.get('f', u'')
            e = dic.get('e', u'')
            bc = dic.get('bc', u'')
            rc = dic.get('rc', u'')
            dc = dic.get('dc', u'')
            rt = dic.get('rt', u'')
            t = dic.get('t', u'')
            try:
                ElevatorStatistics.objects.update_or_create(defaults={'bc': bc, 'rc': rc, 'dc': dc, 'rt': rt, 't': t},
                                                            f=f, e=e)
                data["ret"]["est"].append({"o": "1120", "c": "0", "d": "", "ver": MANUFACTURER_VER, "ses": ses})
                if e:
                    ac = AuthorityCode.objects.filter_active(elevator_code=e).first()
                    if ac:
                        ac.bend_times = int(bc) if bc else 0
                        ac.run_times = int(rc) if rc else 0
                        ac.open_times = int(dc) if dc else 0
                        ac.up_time = int(rt) if rt else 0
                        ac.save()
            except:
                pass
        if not TO_GOV:
            return JsonResponse(data)
            # l.append({'e': e, 'c': '0', 'd': 'success', 'ver': MANUFACTURER_VER, 'ses': ses})
        # return JsonResponse({"ret": {
        #     "est": l
        # }
        # })
        url = HOST + 'api/platform/odev/est.json'
        x_ses = self.request.data.get('ses', None)
        ses = PlatformSession.objects.filter_active().order_by("-id").first().ses
        data = self.request.data
        data['ses'] = ses
        res = requests.post(url, json=data)
        if res.status_code == 200:
            res = res.json()
            try:
                for dic in res['ret']['est']:
                    dic['ses'] = x_ses
            except Exception as e:
                logger.info(json.dumps(res))
        else:
            res = {"ret": {
                "er": [
                    {"o": None, "c": "12", "d": "市局报错了", "ver": MANUFACTURER_VER, "ses": ses},
                    ]
                }
                }
        return JsonResponse(res)


class GetElOnlineView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        online_info = self.request.data.get("OnlineInfo", None)
        if not online_info:
            return JsonResponse({
                "ret": {
                    "OnlineInfo": [{
                        "c": "1",
                        "d": "格式错误",
                        "ver": "2.0",
                        "allEl": "0",
                        "Online": "0",
                        "Maintenance": "0",
                        "alarm": "0"}]
                }})
        lc_id = online_info.get("id", None)
        lc_ac = online_info.get("ac", None)
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "OnlineInfo": [{
                        "c": "1",
                        "d": "鉴权码错误",
                        "ver": "2.0",
                        "allEl": "0",
                        "Online": "0",
                        "Maintenance": "0",
                        "alarm": "0"}]
                }})
        # TODO 市民中心的电梯
        allEl = ElevatorInfo.objects.filter_active().count()
        Online = ElevatorInfo.objects.filter_active().count()
        Maintenance = ElevatorInfo.objects.filter_active().count()
        Alarm = 0
        return JsonResponse({
            "ret": {
                "OnlineInfo": [{
                    "c": "0",
                    "d": "",
                    "ver": "2.0",
                    "allEl": allEl,
                    "Online": Online,
                    "Maintenance": Maintenance,
                    "alarm": Alarm}]
            }})


class GetRegCodeView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        online_info = self.request.data.get("OnlineInfo", None)
        if not online_info:
            return JsonResponse({
                "ret": {
                    "regcode": [{
                        "c": "1",
                        "d": "格式错误",
                        "ver": "2.0",
                        "num": "0",
                        "regcode": ""}]}
            })
        lc_id = online_info.get("id", None)
        lc_ac = online_info.get("ac", None)
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "regcode": [{
                        "c": "1",
                        "d": "鉴权码错误",
                        "ver": "2.0",
                        "num": "0",
                        "regcode": ""}]}
            })

        num = ElevatorInfo.objects.filter_active().count()
        regcode = ElevatorInfo.objects.filter_active().values_list("register_code", flat=True).distinct()
        return JsonResponse({
            "ret": {
                "regcode": [{
                    "c": "0",
                    "d": "",
                    "ver": "2.0",
                    "num": num,
                    "regcode": ",".join(list(regcode)) if regcode else ""
                }]}
        })


class GetElInfoView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        el_info = self.request.data.get("ElInfo", None)
        if not el_info:
            return JsonResponse({
                "ret": {
                    "ElInfo": [{
                        "c": "1",
                        "d": "格式错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": ""
                    }]}
            })
        lc_id = el_info.get("id", None)
        lc_ac = el_info.get("ac", None)
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "ElInfo": [{
                        "c": "1",
                        "d": "鉴权码错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": ""
                    }]}
            })
        reg_code = el_info.get("Regcode", "")
        elevator = ElevatorInfo.objects.filter_active(register_code=reg_code).first()
        mainten = ""
        user = ""
        oper = ""
        e_type = ""
        if elevator:
            e_type = elevator.get_elevator_type_display()
            mainten = elevator.maintain_company_name
            user = elevator.property_company_name
            eps = ElevatorPersonInfo.objects.filter(elevator=elevator)
            if eps:
                names = [ep.worker.auth_user.real_name for ep in eps]
                oper = ",".join(names)

        return JsonResponse({
            "ret": {
                "ElInfo": [{
                    "c": "0",
                    "d": "",
                    "ver": "2.0",
                    "regcode": reg_code,
                    "mainten": mainten,
                    "user": user,
                    "oper": oper,
                    "type": e_type,
                }]}
        })


class GetAlarmInfoView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        alarm_info = self.request.data.get("AlarmInfo", None)
        if not alarm_info:
            return JsonResponse({
                "ret": {
                    "AlarmInfo": [{
                        "c": "1",
                        "d": "格式错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": "",
                        "sendtime": "",
                        "endtime": "",
                        "alarm": ""
                    }]}
            })
        lc_id = alarm_info.get("id", None)
        lc_ac = alarm_info.get("ac", None)
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "AlarmInfo": [{
                        "c": "1",
                        "d": "鉴权码错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": "",
                        "sendtime": "",
                        "endtime": "",
                        "alarm": ""
                    }]}
            })
        reg_code = alarm_info.get("Regcode", "")
        elevator = ElevatorInfo.objects.filter_active(register_code=reg_code).first()
        mainten = ""
        user = ""
        oper = ""
        if elevator:
            mainten = elevator.maintain_company_name
            user = elevator.property_company_name
            eps = ElevatorPersonInfo.objects.filter(elevator=elevator)
            if eps:
                names = [ep.worker.auth_user.real_name for ep in eps]
                oper = ",".join(names)

        qs = ElevatorFault.objects.filter_active(e=reg_code).order_by("id")

        data = {
            "ret": {
                "ElInfo": [
                ]}
        }
        circle = 0
        for ef in qs:
            if ef.s == 'e' and circle == 0:
                dic = {
                    "c": "0",
                    "d": "",
                    "ver": "2.0",
                    "regcode": reg_code,
                    "mainten": mainten,
                    "user": user,
                    "oper": oper,
                    "alarm": get_alarm(ef.a),
                    "sendtime": get_time(ef.t)
                }
                circle = 1
            if ef.s == 'c' and circle == 1:
                dic['endtime'] = get_time(ef.t)
                data['ret']['ElInfo'].append(dic)
                circle = 0
        if circle == 1:
            dic['endtime'] = ''
            data['ret']['ElInfo'].append(dic)
        return JsonResponse(data)


class GetMaintenanceInfoView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        maintain_info = self.request.data.get("MaintenanceInfo", None)
        if not maintain_info:
            return JsonResponse({
                "ret": {
                    "MaintenanceInfo": [{
                        "c": "1",
                        "d": "格式错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": "",
                        "time": "",
                        "endtime": "",
                        "type": "",
                        "content": ""
                    }]}
            })
        lc_id = maintain_info.get("id", None)
        lc_ac = maintain_info.get("ac", None)
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "MaintenanceInfo": [{
                        "c": "1",
                        "d": "鉴权码错误",
                        "ver": "2.0",
                        "regcode": "",
                        "mainten": "",
                        "user": "",
                        "oper": "",
                        "time": "",
                        "endtime": "",
                         "type": "",
                         "content": "",
                    }]}
            })
        reg_code = maintain_info.get("Regcode", "")
        elevator = ElevatorInfo.objects.filter_active(register_code=reg_code).first()
        data = {
            "ret": {
                "MaintenanceInfo": [
                ]}
        }

        if elevator:
            ts = Task.objects.filter_active(elevator=elevator)
            for t in ts:
                ids = json.loads(t.worker)
                ps = Person.objects.filter_active(id__in=ids)
                dic = {
                    "c": "0",
                    "d": "",
                    "ver": "2.0",
                    "regcode": reg_code,
                    "mainten": t.elevator.maintain_company_name,
                    "user": t.elevator.property_company_name,
                    "oper": ",".join([p.auth_user.real_name for p in ps]),
                    "time": str(t.day),
                    "endtime": t.task_end_time.strftime("%Y-%m-%d") if t.task_end_time else "",
                    "type": get_maintain_type(t.maintain_type),
                    "content": json.loads(t.result).get("maintenance_report", "") if t.result else "",
                }
                data['ret']['MaintenanceInfo'].append(dic)
        return JsonResponse(data)


class GetElevatorStatusInfoView(AuthenticationExceptView, WdAPIView):

    def post(self, request, *args, **kwargs):
        lc_id = self.request.data.get("id", None)
        lc_ac = self.request.data.get("ac", None)
        ver = self.request.data.get("ver", None)
        e = self.request.data.get("e", None)
        if not lc_id or not lc_ac or not ver or not e:
            return JsonResponse({
                "ret": {
                    "c": "1",
                    "d": "格式错误",
                    "ver": ver,
                    "es": []
                }
            })
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "c": "1",
                    "d": "鉴权失败",
                    "ver": ver,
                    "es": []
                }
            })

        url = RLHOST
        ses = User.objects.filter_active().order_by("-id").first().session
        url += "&regcode=" + e + "&ses=" + ses
        handler_lc_request_for_status(e, ses)
        es = ElevatorStatus.objects.filter_active(e=e).first()
        dic = dict()
        if es:
            dic['f'] = es.f
            dic['e'] = e
            dic['o'] = es.o
            dic['u'] = es.u
            dic['d'] = es.d
            dic['lm'] = es.lm
            dic['rs'] = es.rs
            dic['od'] = es.od
            dic['om'] = es.om
            dic['sd'] = es.sd
            dic['sm'] = es.sm
            dic['ob'] = es.ob
            dic['dz'] = es.dz
            dic['ol'] = es.ol
            dic['fl'] = es.fl
            dic['ps'] = es.ps
            dic['cp'] = es.cp
            dic['t'] = es.t
        return JsonResponse({
            "ret": {
                "c": "0",
                "d": "success",
                "ver": ver,
                "es": [dic]
            }
        })


class GetElevatorFaultInfoView(AuthenticationExceptView, WdAPIView):
    def post(self, request, *args, **kwargs):
        lc_id = self.request.data.get("id", None)
        lc_ac = self.request.data.get("ac", None)
        ver = self.request.data.get("ver", None)
        e = self.request.data.get("e", None)
        t1 = self.request.data.get("t1", None)
        t2 = self.request.data.get("t2", None)
        if not lc_id or not lc_ac or not ver or not e or not t1 or not t2:
            return JsonResponse({
                "ret": {
                    "c": "1",
                    "d": "格式错误",
                    "ver": ver,
                    "e": e,
                    "t1": t1,
                    "t2": t2,
                    "ef": []
                }
            })
        if not is_lc(lc_id=lc_id, lc_ac=lc_ac):
            return JsonResponse({
                "ret": {
                    "c": "1",
                    "d": "鉴权失败",
                    "ver": ver,
                    "e": e,
                    "t1": t1,
                    "t2": t2,
                    "ef": []
                }
            })
        try:
            time_from = datetime.datetime.strptime(t1, "%Y%m%d")
            time_to = datetime.datetime.strptime(t2, "%Y%m%d")
        except:
            return JsonResponse({
                "ret": {
                    "c": "1",
                    "d": "格式错误",
                    "ver": ver,
                    "e": e,
                    "t1": t1,
                    "t2": t2,
                    "ef": []
                }
            })
        efs = ElevatorFault.objects.filter_active(e=e, update_time__gte=time_from, update_time__lt=time_to)
        if not efs:
            ac = AuthorityCode.objects.filter_active(elevator_code=e).first()
            if ac:
                o = ac.device_code_elevator
                efs = ElevatorFault.objects.filter_active(o=o, update_time__gte=time_from, update_time__lt=time_to)
        ef = []
        for obj in efs:
            dic = dict()
            dic['s'] = obj.s
            dic['a'] = obj.a
            dic['er'] = obj.er
            dic['t'] = obj.t
            ef.append(dic)
        return JsonResponse({
            "ret": {
                "c": "0",
                "d": "success",
                "ver": ver,
                "e": e,
                "t1": t1,
                "t2": t2,
                "ef": ef
            }
        })






























